from django.contrib.contenttypes.models import ContentType
from django.core.paginator import (EmptyPage, InvalidPage, PageNotAnInteger,
                                   Paginator)
from django.db.models import F, Q
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

from comment.models import Comment
from friendship.models import Follow
from mood import models
from utils.base64_to_image import base64_to_image
from .forms.mood import MoodModelForm


# Create your views here.

class Mood(View):
    def get(self, request):
        # 发布心情&评论表单
        intro_form = MoodModelForm()
        # img_form = MoodImageModelForm()

        # items = models.Mood.objects.all()
        # context = items.get_context(request)
        # 所有符合条件的心情对象。
        friends = Follow.my_friends(request.universe.user)
        data = models.Mood.objects.filter(is_delete=0).filter(
            Q(is_public=1) |  # 1. 公开可见的心情
            Q(is_public=2, author__in=friends) |  # 2. 查看好友的心情
            # Q(is_public=3, author=request.universe.user) |      # 3. 私人可见的心情
            Q(author=request.universe.user)  # 4. 登录者本人发的心情, 包括私人心情
        ).all().order_by('-create_datetime')

        # 取出心情评论

        # imgs = models.MoodImage.objects.filter(author=request.universe.user).all()
        # 每个data怎么把多张图片地址关联上------(解决了)

        # 分页显示
        paginator = Paginator(data, 4)
        page_num = int(request.GET.get('page', 1))
        try:
            data = paginator.page(page_num)
        except PageNotAnInteger:
            data = paginator.page(1)
        except(EmptyPage, InvalidPage):
            data = paginator.page(paginator.num_pages)

        return render(request, 'mood/mood_index.html', {'intro_form': intro_form,
                                                        'data': data})

    def post(self, request):
        print('发布心情，上传图片-----------')
        intro_form = MoodModelForm(data=request.POST)
        # print(request.POST.getlist('image[]'))
        # print(request.POST.get('intro'))
        # print(request.POST.get('image_list[]')) #拿到base64列表
        # print(request.POST.get('image[]'))
        # base64_arr1 = request.POST.get('image_list[]')
        # base64_arr2 = request.POST('image')

        # img_form = ImgModelForm(data=request.POST)
        if intro_form.is_valid():

            intro_form.instance.author = request.universe.user
            intro_form.save()

            image_list = request.POST.getlist('image[]')
            print('%s: 本次上传%s张图片' % (request.universe.user.username, len(image_list)))
            if len(image_list) <= 4:
                for img in image_list:
                    file_url, thumbnail_url = base64_to_image(img, intro_form.instance.id)
                    print('file_url:{0}'.format(file_url))
                    print('thumbnail_url:{0}'.format(thumbnail_url))
                    models.MoodImage.objects.create(mood=intro_form.instance,
                                                    file_url=file_url,
                                                    thumbnail_url=thumbnail_url,
                                                    author=request.universe.user)
            else:
                return JsonResponse({'status': False, 'error': '您上传的图片太多啦！只能传一张图片哦。'})

            return JsonResponse({'status': True, 'data': '/mood/'})

        return JsonResponse({'status': False, 'error': intro_form.errors})


class MoodImageList(View):
    def get(self, request):
        # friends = Follow.my_friends(request.universe.user)
        # data = models.Mood.objects.filter(is_delete=0).all().order_by('-create_datetime')
        data = models.MoodImage.objects.filter(mood__is_delete=False).all().order_by('-create_datetime')

        # 取出心情评论

        # imgs = models.MoodImage.objects.filter(author=request.universe.user).all()
        # 每个data怎么把多张图片地址关联上------(解决了)

        # 分页显示
        paginator = Paginator(data, 30)
        page_num = int(request.GET.get('page', 1))
        try:
            data = paginator.page(page_num)
        except PageNotAnInteger:
            data = paginator.page(1)
        except(EmptyPage, InvalidPage):
            data = paginator.page(paginator.num_pages)

        return render(request, 'mood/mood_image_list.html', {'data': data})


class MoodDetail(View):
    def get(self, request, mood_id):
        friends = Follow.my_friends(request.universe.user)
        # mood_post = models.Mood.objects.filter(pk=mood_id, is_delete=0).first()
        mood_post = get_object_or_404(models.Mood, pk=mood_id, is_delete=0)
        content_type = ContentType.objects.get_for_model(mood_post)

        if mood_post.is_public == 1:
            comments = Comment.objects.filter(content_type=content_type, object_id=mood_post.pk).all()

            # paginator = Paginator(comments, 5)
            # page_num = int(request.GET.get('page', 1))
            # try:
            #     comments = paginator.page(page_num)
            # except PageNotAnInteger:
            #     comments = paginator.page(1)
            # except(EmptyPage, InvalidPage):
            #     comments = paginator.page(paginator.num_pages)

            return render(request, 'mood/mood_detail.html', {'mood_post': mood_post, 'comments': comments})
        elif mood_post.is_public == 2:
            if (mood_post.author in friends) or (mood_post.author == request.universe.user):
                comments = Comment.objects.filter(content_type=content_type, object_id=mood_post.pk).all()
                return render(request, 'mood/mood_detail.html', {'mood_post': mood_post, 'comments': comments})
        elif mood_post.is_public == 3:
            if mood_post.author == request.universe.user:
                comments = Comment.objects.filter(content_type=content_type, object_id=mood_post.pk).all()
                return render(request, 'mood/mood_detail.html', {'mood_post': mood_post, 'comments': comments})

        return JsonResponse({'status': False, 'error': '系统错误'})

@csrf_exempt
def mood_like(request):
    if request.method == 'POST':
        mood_id = request.POST.get('mood_id')
        print(mood_id)
        data = False
        mood_like_object = models.MoodLiker.objects.filter(mood_id=mood_id, user=request.universe.user)
        if not mood_like_object:
            print('你还没有点赞，现在点赞')
            models.MoodLiker.objects.create(mood_id=mood_id, user=request.universe.user)
            models.Mood.objects.filter(pk=mood_id).update(like_amount=F('like_amount') + 1)
            # 点亮爱心
            data = True
        else:
            print('你已经点过赞，取消点赞')
            mood_like_object.delete()
            models.Mood.objects.filter(pk=mood_id).update(like_amount=F('like_amount') - 1)
            # 取消点亮
            data = False
        return JsonResponse({'status': True, 'data': data})

    return JsonResponse({'status': False, 'error': '点赞错误'})

def mood_delete(request, mood_id):
    models.Mood.objects.filter(id=mood_id, author=request.universe.user).update(is_delete=True)

    return redirect('/mood/')

    # url = reverse('mood', kwargs={'mood_id': mood_id})
    # return redirect(url)

def mood_test(request):
    if request.method == 'GET':
        return render(request, 'mood/mood_test.html')
